<?php
namespace app\admin\service;


use app\model\Admin;
use app\model\AuthGroup;
use app\model\AuthGroupAdmin;
use app\model\AuthRule;

/**
 * Class RbacService
 * @package app\service
 */
class RbacService extends CommonService
{
    /**
     * 检查用户的权限
     * @param $admin_id
     * @param $path
     */
    public static function checkAuth($path, $admin, $group)
    {
        // 超级管理员不检查权限
        if ($admin['is_admin'] == 1)
        {
            return true;
        }

        // 处理链接参数
        $path = strtolower($path);
        $pathArr = explode("/", $path);
        $addon = $pathArr[0];   // 所属插件
        array_shift($pathArr);
        $url = implode("/", $pathArr);  // 菜单表的链接

        // 用户的菜单权限ID
        $ruleIds = explode(",", $group['rules']);

        // 获取菜单
        $authRule = AuthRule::getOne(['addon' => $addon, 'url' => $url, 'status' => 1]);
        if (empty($authRule))
        {
            return false;
        }

        // 特殊不需要权限的菜单直接返回
        if ($authRule['is_control'] == 0)
        {
            return true;
        }

        // 访问的页面不在授权范围之内
        if (!in_array($authRule['id'], $ruleIds))
        {
            return false;
        }
        return false;
    }

    /**
     * 获取管理员列表
     */
    public static function getAdminList($request)
    {
        $where = [];
        if (!empty($request['username']))
        {
            $where[] = ['username', 'like', '%' . $request['username'] . '%'];
        }
        if (!empty($request['nickname']))
        {
            $where[] = ['nickname', 'like', '%' . $request['nickname'] . '%'];
        }
        $list = Admin::getPageList($where);

        // 获取管理员所属角色
        $adminIds = array_column($list['data'], 'id');
        $authGroup = AuthGroup::getAdminGroupList($adminIds);
        $groups = array_column($authGroup, 'title', 'uid');
        $groupIds = array_column($authGroup, 'group_id', 'uid');
        foreach ($list['data'] as &$item)
        {
            $item['groupTitle'] = $groups[$item['id']] ?? '';
            $item['groupId'] = $groupIds[$item['id']] ?? '';
        }
        return $list;
    }

    /**
     * 编辑
     */
    public static function editAdmin($data)
    {
        $groupId = $data['groupid'] ?? 0;
        unset($data['groupid']);
        // 密码处理
        if (empty($data['password']))
        {
            unset($data['password']);
        } else {
            $data['password'] = LoginService::password($data['password']);
        }
        if (!empty($data['id']))
        {
            Admin::updateOne($data, ['id' => $data['id']]);
            AuthGroupAdmin::updateOne(['group_id' => $groupId], ['uid' => $data['id']]);
        } else {
            $uid = Admin::addOne($data, true);
            AuthGroupAdmin::addOne(['uid' => $uid, 'group_id' => $groupId]);
        }
        return true;
    }

    /**
     * 删除
     * @param $data
     * @return bool
     */
    public static function delAdmin($data)
    {
        return Admin::deleteByIds($data);
    }

    /**
     * 获取单个
     * @param $request
     * @return array
     */
    public static function getAdmin($request)
    {
        $result = $where = [];
        if (!empty($request['id']))
        {
            $result = Admin::getById($request['id']);
            $result['group_id'] = self::getAdminGroupId($request['id']);
        }
        return $result;
    }

    /**
     * 获取分组列表
     * @param $request
     * @return array
     */
    public static function getRoleList()
    {
        $list = AuthGroup::getList();
        return $list;
    }

    /**
     * @desc 获取admin的groupid列表
     * @return array
     */
    public static function getAdminRoleList()
    {
        $list = AuthGroup::getList();
        return array_column($list, 'title', 'id');
    }

    /**
     * 编辑分组
     * @return bool
     */
    public static function editRole($data)
    {
        if (!empty($data['id']))
        {
            AuthGroup::updateOne($data, ['id' => $data['id']]);
        } else {
            AuthGroup::addOne($data);
        }
        return true;
    }

    /**
     * 获取单个角色
     * @return array
     */
    public static function getRole($request)
    {
        $result = $where = [];
        if (!empty($request['id']))
        {
            $result = AuthGroup::getById($request['id']);
        }
        return $result;
    }

    /**
     * 删除
     * @param $data
     * @return bool
     */
    public static function delRole($data)
    {
        return AuthGroup::deleteByIds($data);
    }

    /**
     * 获取树状分组的权限
     */
    public static function getRuleList($groupId)
    {
        $menuList = AuthRule::getList([], 'id,title,pid', 'sort DESC, id ASC');
        $ruleList = AuthGroup::getVal(['id' => $groupId], 'rules');
        $rules = explode(",", $ruleList);
        foreach ($menuList as &$item)
        {
            if (in_array($item['id'], $rules))
            {
                $item['checked'] = true;
            } else {
                $item['checked'] = false;
            }
        }
        return $menuList;
    }

    /**
     * @desc 获取admin的groupid
     * @param $adminId
     */
    public static function getAdminGroupId($adminId)
    {
        $result = AuthGroupAdmin::getOne(['uid' => $adminId]);
        return $result['group_id'];
    }

    public static function isAdmin($adminId)
    {
        $admin = Admin::getById($adminId);
        return $admin['is_admin'];
    }
}